//
//  ViewController.swift
//  PokeMon-main
//
//  Created by 安爹的Mac on 16/7/17.
//  Copyright © 2016年 安爹的苹果机. All rights reserved.
//

import UIKit
import AVFoundation

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UISearchBarDelegate {
    
    @IBOutlet weak var pokeCollectionView: UICollectionView?
    @IBOutlet weak var searchBar: UISearchBar!
    
    var pokemon = [Pokemon]()
    var filteredPokemon = [Pokemon]()
    var musicPlayer: AVAudioPlayer!
    var inSearchMode = false
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.pokeCollectionView?.delegate = self
        self.pokeCollectionView?.dataSource = self
        self.searchBar.delegate = self
        initAudio()
        parsePokemonCSV()
    }

    func parsePokemonCSV() {
        let bundle = NSBundle.mainBundle().pathForResource("pokemon", ofType: "csv")
        do {
            let csv = try CSV(contentsOfURL: bundle!)
            let rows = csv.rows
            for item in rows {
                
                let pokeId = Int(item["id"]!)!
                let name = item["identifier"]!
                let poke = Pokemon(name: name, pokedexId: pokeId)
                pokemon.append(poke)
                
            }
            
            
        } catch let err as NSError{
            print(err.debugDescription)
        }
    }
    
    func initAudio() {
        let path = NSBundle.mainBundle().pathForResource("music", ofType: "mp3")!
        do {
            musicPlayer = try AVAudioPlayer(contentsOfURL: NSURL(string: path)!)
            musicPlayer.prepareToPlay()
            musicPlayer.numberOfLoops = -1
            musicPlayer.play()
        } catch let err as NSError {
            print(err.debugDescription)
        }
    }
    
    
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if inSearchMode {
            return filteredPokemon.count
        } else {
            return pokemon.count
        }
    }
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 1
    }
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        searchBar.resignFirstResponder()
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        var selectpoke: Pokemon!
        if inSearchMode {
            selectpoke = filteredPokemon[indexPath.row]
        } else {
            selectpoke = pokemon[indexPath.row]
        }
        performSegueWithIdentifier("PokemonDetailVC", sender: selectpoke)
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        if let cell = collectionView.dequeueReusableCellWithReuseIdentifier("PokeCell", forIndexPath: indexPath) as? PokeCell {
            //let pokemon = Pokemon(name: "Test", pokedexId:(indexPath.row+1))
            if inSearchMode {
                cell.configureCell(filteredPokemon[indexPath.row])
            } else {
                cell.configureCell(pokemon[indexPath.row])
            }
            return cell
        } else {
            return UICollectionViewCell()
        }
    }
    
    @IBAction func playMusicBtnPressed(sender: UIButton!) {
        if musicPlayer.playing {
            musicPlayer.stop()
            sender.alpha = 0.2
        } else {
            musicPlayer.play()
            sender.alpha = 1.0
        }
    }
    
    
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
        return CGSizeMake(105, 105)
    }


    func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
        if searchBar.text == nil || searchBar.text == "" {
            inSearchMode = false
            self.pokeCollectionView?.reloadData()
        } else {
            inSearchMode = true
            let lower = searchBar.text!.lowercaseString
            // 过滤包含有关键字的Element
            
            filteredPokemon = pokemon.filter({$0.name.rangeOfString(lower) != nil})
            pokeCollectionView?.reloadData()
        }
    }
    
    func searchBarSearchButtonClicked(searchBar: UISearchBar) {
        view.endEditing(true)
    }
    
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "PokemonDetailVC" {
            if let detailVC = segue.destinationViewController as? PokemonDetailVC {
                if let pokes = sender as? Pokemon {
                    detailVC.selectpoke = pokes
                    print("传递数据！")
                }
            }
        }
    }
}

